package br.gen.seam.sqlserver.extract.schema;

import br.gen.seam.util.entity.Schema;
import br.gen.seam.util.jdbc.AbstractConnection;
import br.gen.seam.util.jdbc.exception.JDBCException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Diego Araujo | diegogomesaraujo@gmail.com
 * @version 1.0
 */
public class ExtractSchemas {

    private AbstractConnection connection;
    
    private String database;

    private List<Schema> schemas;

    public ExtractSchemas(String database) {
        this.database = database;
        connection = AbstractConnection.getInstance();
    }

    private void getInformations() throws SqlServerExtractSchemaException {
        try {
            connection.openConnection();
            connection.execute("SELECT CATALOG_NAME, SCHEMA_NAME "
                    + "FROM INFORMATION_SCHEMA.SCHEMATA "
                    + "WHERE CATALOG_NAME='" + database + "' "
                    + "ORDER BY SCHEMA_NAME");
        } catch (JDBCException ex) {
            throw new SqlServerExtractSchemaException("Error when extracting schemas: " + ex.getMessage(), ex);
        }
    }

    private void extractInformations() throws SqlServerExtractSchemaException {
        try {
            getInformations();
            ResultSet resultSet = connection.getResultSet();
            schemas = new ArrayList<Schema>();
            while (resultSet.next()) {
                Schema schema = new Schema();
                schema.setName(resultSet.getString("SCHEMA_NAME"));
                schemas.add(schema);
            }
            connection.closeConnection();
        } catch (JDBCException ex) {
            throw new SqlServerExtractSchemaException("Error when extracting schemas: " + ex.getMessage(), ex);
        } catch (SQLException ex) {
            throw new SqlServerExtractSchemaException("Error when extracting schemas: " + ex.getMessage(), ex);
        }
    }

    public List<Schema> getSchemas() throws SqlServerExtractSchemaException {
        extractInformations();
        return schemas;
    }
}
